package com.hup.joystick.service;

import com.hup.utils.commons.exception.AppExceptionHandler;
import com.hup.utils.io.audio.AudioInfo;
import com.hup.utils.io.audio.AudioPlayTask.TaskListener;
import com.hup.utils.io.audio.ClipPlayTask;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;

import java.util.function.Consumer;

/**
 * @author hugan
 * @date 2023/1/24
 */
@Log4j2
@Component
public class AudioService {

    private ClipPlayTask audioConnected;
    private ClipPlayTask audioDisconnected;
    /**
     * 静音
     */
    @Getter
    @Setter
    private boolean mute;

    public AudioService() {
        initAudio("/audio/WindowsHardwareInsert.wav", "连接", clipPlayTask -> audioConnected = clipPlayTask);
        initAudio("/audio/WindowsHardwareRemove.wav", "断开", clipPlayTask -> audioDisconnected = clipPlayTask);
    }

    private void initAudio(String path, String desc, Consumer<ClipPlayTask> consumer) {
        ClipPlayTask clipPlayTask = new ClipPlayTask(path, new TaskListener<ClipPlayTask>() {
            @Override
            public void onGetInfo(AudioInfo audioInfo, Exception e, ClipPlayTask task) {
                if (audioInfo != null) {
                    task.getMasterGain().setValue(-1);
                } else {
                    AppExceptionHandler.handle("[" + desc + "]音效加载错误:", e);
                }
            }
        });
        consumer.accept(clipPlayTask);
    }

    public void connected() {
        if (mute) return;
        audioConnected.play();
    }

    public void disconnected() {
        if (mute) return;
        audioDisconnected.play();
    }

}
